import { default as ndarray } from 'ndarray';
import { differenceRGB } from './colorSimilarityCal';
export default function getPixels(imgSrc: string) {
  return new Promise<ndarray.NdArray>((resolve, reject) => {
    _getPixels(imgSrc, function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data as ndarray.NdArray);
      }
    });
  });
}
function _getPixels(
  url: string,
  cb: (err: string | Event | null, ndarray: ndarray.NdArray | null) => void
) {
  const img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function () {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const context = canvas.getContext('2d');
    context!.drawImage(img, 0, 0);
    const pixels = context!.getImageData(0, 0, img.width, img.height);
    cb(
      null,
      ndarray(
        new Uint8Array(pixels.data),
        [img.width, img.height, 4],
        [4, 4 * img.width, 1],
        0
      )
    );
  };
  img.onerror = function (err) {
    cb(err, null);
  };
  img.src = url;
}

export function handlePixels(
  imgData: ndarray.NdArray,
  diffLevel = 10,
  colorCount = 8
) {
  const colorPixelsMap = {};
  const [width, height] = imgData.shape;
  for (let x = 0; x < width; ++x) {
    for (let y = 0; y < height; ++y) {
      const r = imgData.get(x, y, 0);
      const g = imgData.get(x, y, 1);
      const b = imgData.get(x, y, 2);

      // 获取使用最多的颜色
      const k = [r, g, b].join();
      if (!colorPixelsMap[k]) {
        colorPixelsMap[k] = { times: 0, pixels: [], rgb: k };
      }
      colorPixelsMap[k]['pixels'].push([x, y].join());
      colorPixelsMap[k]['times']++;

      // 计算相似度
      // const color = getColorPixel([r, g, b], paletteList)
      // if (!colorPixelsMap[color]) {
      //     colorPixelsMap[color] = []
      // } else {
      //     colorPixelsMap[color].push({ x, y })
      // }
    }
  }

  // 将所有的颜色排序
  const sortedColorsList = Object.values(colorPixelsMap).sort(
    (a, b) => b.times - a.times
  );

  console.log('一共获取到的颜色数量：', sortedColorsList.length);

  // 获取最多的几种颜色
  const mostColorsList = [sortedColorsList[0].rgb];

  let i = 1;
  while (i < sortedColorsList.length) {
    const current_rgb = sortedColorsList[i].rgb;
    // 从mostColorsList中获取与当前色最相似的颜色
    let diff = null,
      similarColor = null;
    mostColorsList.forEach((mc) => {
      const _diff = differenceRGB(mc.split(','), current_rgb.split(','));
      if (!diff || _diff < diff) {
        diff = _diff;
        similarColor = mc;
      }
    });
    if (diff > diffLevel && mostColorsList.length < colorCount) {
      mostColorsList.push(current_rgb);
    } else {
      const similarColorObj = colorPixelsMap[similarColor];
      const { pixels, times } = colorPixelsMap[current_rgb];

      similarColorObj.pixels.push(...pixels);
      similarColorObj.times = similarColorObj.times + times;
      delete colorPixelsMap[current_rgb];
    }
    ++i;
  }

  return { colorPixelsMap, mostColorsList };
}
